package com.eatme.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.List;
import java.util.Iterator;

import com.eatme.model.BasicList;

public class HibernateBasicListDao implements BasicListDao {

    private SessionFactory factory;

    /**
     * Setter for session factory. Spring will use this to inject the session
     * factory into the dao.
     *
     * @param factory hibernate session factory
     */
    public void setSessionFactory(SessionFactory factory) {
        this.factory = factory;
    }

    /**
     * Helper method for retrieving hibernate session
     *
     * @return hibernate session
     */
    protected Session getSession() {
        return factory.getCurrentSession();
    }

    /**
     * Load a {@link com.eatme.model.BasicList} from the DB, given it's <tt>id</tt> .
     *
     * @param id The id of the Contact to load.
     * @return Contact
     */
    public BasicList load(long id) {
        return (BasicList) getSession().get(BasicList.class, new Long(id));
    }

    /**
     * Save the contact to the DB
     *
     * @param contact
     * @return persistent instance of contact
     */
    public BasicList save(BasicList contact) {
        return (BasicList) getSession().merge(contact);
    }

    /**
     * Delete a {@link com.eatme.model.BasicList} from the DB, given it's <tt>id</tt>.
     *
     * @param id The id of the Contact to delete.
     */
    public void delete(long id) {
        getSession().delete(load(id));
    }

    /**
     * Query the DB, using the supplied query details.
     *
     * @param qp Query Parameters to use.
     * @return The results of the query as an Iterator.
     */
    @SuppressWarnings("unchecked")
    public Iterator<BasicList> find(final QueryParam qp, BasicList filterBasicList) {
        return buildFindQuery(qp, filterBasicList, false).list().iterator();
    }

    /**
     * Return the number of Contacts in the DB.
     *
     * @return count
     */
    public int count(BasicList filterBasicList) {
        return ((Long) buildFindQuery(null, filterBasicList, true).uniqueResult())
                .intValue();
    }

    /**
     * Returns a list of unique last names
     */
    @SuppressWarnings("unchecked")
    public List<String> getUniqueLastNames() {
        return getSession().createQuery(
                "select distinct target.secondField "
                        + " from BasicList target order by target.secondField")
                .list();
    }

    /**
     * builds a query object to satisfy the provided parameters
     *
     * @param qp     sorting and paging criteria
     * @param filterBasicList filter criteria
     * @param count  true if this is a query meant to retrieve the number of rows
     * @return query object that satisfies the provided criteria
     */
    protected Query buildFindQuery(QueryParam qp, BasicList filterBasicList, boolean count) {
        HibernateBasicListFinderQueryBuilder builder = new HibernateBasicListFinderQueryBuilder();
        builder.setQueryParam(qp);
        builder.setFilter(filterBasicList);
        builder.setCount(count);
        Query query = getSession().createQuery(builder.buildHql());
        query.setParameters(builder.getParameters(), builder.getTypes());
        if (!count && qp != null) {
            query.setFirstResult(qp.getFirst()).setMaxResults(qp.getCount());
        }
        return query;
    }

}
